
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '../routers/router.js'



const service = axios.create({
    baseURL: 'http://localhost:6062', // 后端地址
    timeout: 5000
})

export default service

// 请求拦截器
service.interceptors.request.use(config => {
    const userStore = useUserStore()
    if (userStore.token) {
        config.headers.Authorization = `Bearer ${userStore.token}`
    }
    return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        const router = useRouter()

        if (response.config.url.includes('/register') && res.code === 200) {
            ElMessage.success('注册成功！即将跳转登录页面')
            setTimeout(() => {
                router.push({
                    name: 'Login',
                    query: {
                        fromRegister: 'true',
                        username: response.config.data?.username || ''
                    }
                })
            }, 1500)
            return res
        }

        if (res.code !== 200) {
            ElMessage.error(res.message || 'Error')
            return Promise.reject(new Error(res.message || 'Error'))
        }
        return res
    },
    error => {
        const router = useRouter()
        let errorMessage = '请求失败'

        if (error.response) {
            switch (error.response.status) {
                case 401:
                    errorMessage = '登录已过期，请重新登录'
                    router.push('/login')
                    break
                // 其他状态码处理保持不变
            }
        }
        ElMessage.error(errorMessage)
        return Promise.reject(error)
    }
)

// 封装请求方法
export const useRequest = () => {
    const request = (config) => service({
        ...config,
        headers: {
            'Content-Type': 'application/json',
            ...config.headers
        }
    })

    const get = (url, params) => request({ url, method: 'get', params })
    const post = (url, data) => request({ url, method: 'post', data })

    return { request, get, post }
}

export default service
